<template>
    <AButton
        @click="
            operationType = 'create';
            state.formData = { ...initFormData };
            modalVisible = true;
        "
        type="primary"
        shape="circle"
    >
        <template #icon>
            <PlusOutlined />
        </template>
    </AButton>
    <ATable :pagination="false" :columns="columns" :dataSource="state.dataSource.map((item, index) => ({ ...item, key: index }))">
        <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'operation'">
                <AButton
                    @click="
                        operationType = 'update';
                        state.formData = { ...record, status: record.status ? true : false };
                        state.operatedRecord = record;
                        modalVisible = true;
                    "
                    type="primary"
                    >编辑</AButton
                >
                <AButton
                    @click="
                        state.operatedRecord = record;
                        state.expandedKeys = state.accessList.map(item => item.key);
                        authModalVisible = true;
                        state.roleAccessKeys = [];
                        getRoleAccess();
                    "
                    >授权</AButton
                >
                <APopconfirm @confirm="handleDelete(record)" :title="`确定删除${record.title}吗？`">
                    <AButton type="danger">删除</AButton>
                </APopconfirm>
            </template>
        </template>
    </ATable>
    <AModal @ok="confirmForm" v-model:visible="modalVisible" :title="`${operationType === 'create' ? '添加' : '编辑'}`" :width="600">
        <ARow>
            <ACol span="21">
                <AForm @finish="confirmForm" ref="formRef" :model="state.formData" v-bind="{ labelCol: { span: 6 }, wrapperCol: { span: 18 } }">
                    <AFormItem name="title" label="角色名" :rules="[{ required: true, message: '请输入角色名' }]">
                        <AInput v-model:value="state.formData.title" placeholder="请输入角色名" />
                    </AFormItem>
                    <AFormItem name="status" label="角色状态">
                        <ASwitch v-model:checked="state.formData.status" checkedChildren="可用" unCheckedChildren="禁用" />
                    </AFormItem>
                    <AFormItem name="description" label="角色描述">
                        <ATextarea v-model:value="state.formData.description" :rows="3" placeholder="请输入角色描述" />
                    </AFormItem>
                </AForm>
            </ACol>
            <ACol span="3"> </ACol>
        </ARow>
    </AModal>
    <AModal @ok="confirmAuthForm" okText="确认授权" v-model:visible="authModalVisible" :title="`向${state.operatedRecord.title}授权`" :width="600">
        <ARow>
            <ACol :span="8" />
            <ACol :span="16">
                <ATree
                    ref="treeRef"
                    v-model:expandedKeys="state.expandedKeys"
                    v-model:checkedKeys="state.roleAccessKeys"
                    :treeData="state.accessList"
                    checkable
                />
            </ACol>
        </ARow>
    </AModal>
</template>

<script setup>
import { PlusOutlined } from "@ant-design/icons-vue";
import { reactive, ref, toRefs } from "vue";
import { createRoleApi, deleteRoleApi, getRoleApi, updateRoleApi, getRoleAccessApi, createRoleAccessApi } from "@/api/role";
import { message } from "ant-design-vue";
import { getAccessApi } from "@/api/access";
const columns = [
    {
        dataIndex: "_id",
        title: "ID",
    },
    {
        dataIndex: "title",
        title: "角色名",
    },
    {
        dataIndex: "status",
        title: "状态",
        customRender: ({ text }) => (text ? "可用" : "不可用"),
    },
    {
        dataIndex: "description",
        title: "角色描述",
    },
    {
        title: "操作",
        dataIndex: "operation",
    },
];
const initFormData = {
    title: "",
    description: "",
    status: true,
};
const state = reactive({
    dataSource: [],
    formData: { ...initFormData },
    operatedRecord: {},
    accessList: [],
    roleAccessKeys: [],
    expandedKeys: [],
    requestingKeys: [],
});
const modalVisible = ref(false);
const operationType = ref("create");
const formRef = ref();
const getRole = () => {
    return getRoleApi().then(res => {
        if (res.code === 200) {
            state.dataSource = reactive(res.data);
            return res.data;
        }
    });
};
getRole();
const confirmForm = () => {
    formRef.value.validate().then(result => {
        const body = { ...result, status: result.status ? 1 : 0 };
        if (operationType.value === "create") {
            createRoleApi(body).then(async res => {
                if (res.code === 200) {
                    await getRole();
                    message.success("添加成功");
                    modalVisible.value = false;
                }
            });
        }
        if (operationType.value === "update") {
            updateRoleApi({ _id: state.operatedRecord._id, ...result }).then(async res => {
                if (res.code === 200) {
                    await getRole();
                    message.success("更新成功");
                    modalVisible.value = false;
                }
            });
        }
    });
};
const handleDelete = record => {
    deleteRoleApi({ _id: record._id }).then(async res => {
        if (res.code === 200) {
            await getRole();
            message.success("删除成功");
        }
    });
};
const getRoleAccess = () => {
    getRoleAccessApi(state.operatedRecord._id).then(res => {
        if (res.code === 200) {
            state.roleAccessKeys = res.data.map(item => item.access_id);
            //如果子元素没有被全选，则把父元素的的key删掉
            state.accessList.forEach(item => {
                if (item.children && item.children.length && item.children.some(item1 => !state.roleAccessKeys.includes(item1._id))) {
                    state.roleAccessKeys.forEach((item2, index2) => {
                        if (item2 === item._id) {
                            state.roleAccessKeys.splice(index2, 1);
                        }
                    });
                }
            });
        }
    });
};
const formatAccessList = list => {
    return list.map(item => {
        const formatResult = {
            ...item,
            title: item.module_id
                ? item.module_id === "0"
                    ? item.module_name
                    : (item.type === 2 ? "菜单-" : item.type === 3 ? "接口-" : item.type === 1 ? "" : "") + item.action_name
                : "",
            key: item._id,
        };
        if (item.children) {
            return { ...formatResult, children: formatAccessList(item.children) };
        }
        return formatResult;
    });
};
const getAccess = () => {
    getAccessApi().then(res => {
        if (res.code === 200) {
            state.accessList = formatAccessList(res.data);
        }
    });
};
getAccess();
const authModalVisible = ref(false);
const treeRef = ref();
const confirmAuthForm = () => {
    state.requestingKeys = [...treeRef.value.checkedKeys, ...treeRef.value.halfCheckedKeys];
    createRoleAccessApi({ role_id: state.operatedRecord._id, access_ids: state.requestingKeys }).then(res => {
        if (res.code === 200) {
            message.success("授权成功");
            authModalVisible.value = false;
        }
    });
};
</script>

<style scoped lang="scss"></style>
